<?php

class MultiSortOrder {
	public $name;
	public $direction;
	public $type;
	
	public function __construct($n, $d, $t="field") {
		$this->name = $n;
		$this->direction  = $d;
		$this->type = strtolower($t);
	}
}


class MultiSorter {
	
	public static $orderBy;	
	
	public static function addOrderBy(MultiSortOrder $m) {
		
		if(!is_array(self::$orderBy)) { self::$orderBy = array(); }
		
		array_push(self::$orderBy, $m);
	}
	
	static function sort($arr, $preserveOrderBy = false) {
		
		usort($arr, __CLASS__."::compare");
		if(!$preserveOrderBy) { self::$orderBy = array(); }
		
		return $arr;
		
	}

	public static function compare(&$a, &$b) {
		
		return self::compareColumn($a, $b, 0);
	}
	
	public static function compareColumn(&$a, &$b, $index) {
		
		if(count(self::$orderBy) > $index) {
			
			$o = self::$orderBy[$index];
			
			$column = $o->name;
			
			switch($o->type) {
				case "field":
					$aval = $a[$column];
					$bval = $b[$column];
					break;
				case "attrib":
					$aval = $a->$column;
					$bval = $b->$column;
					break;
				case "func":
					$aval = $a->$column();
					$bval = $b->$column();
					break;
					
			}

			//Set shure that we only compare strings
			$aval = sprintf($aval);
			$bval = sprintf($bval);
			
			//Compare
			if($aval == $bval) { return self::compareColumn($a, $b, ++$index); }
			if($o->direction == "ASC") { return $aval < $bval ? -1: 1; }
			if($o->direction == "DESC") { return $aval > $bval ? -1: 1; }
			
		}
		else {
			return false;
		}
	}
	
}
	

?>